package club.gskj.gulimall.product.config;

import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @ClassName MyChageConfig
 * @Description TODO
 * @Author 康纳
 * @Date 2021-02-16
 */

//@EnableConfigurationProperties(CacheProperties.class) // 绑定properties配置类,默认CacheAutoConfiguration已经绑定了  CacheProperties,这里不用再绑定。
@EnableCaching // 开启缓存功能
@Configuration
public class MyChageConfig {

    /**
     * 自定义 reidsCache配置类
     * 配置文件的配置无效了？  必须让他生效： @EnableConfigurationProperties(CacheProperties.class) // 绑定properties配置类。
     * 1. 和配置文件绑定的配置类
     *
     * @ConfigurationProperties(prefix = "spring.cache")
     * public class CacheProperties
     * <p>
     * 2.从方法传参形式，注入CacheProperties，并将.properties中配置的属性设置到 RedisCacheConfiguration中。实现配置文件的配置有效果。
     */
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
        //System.out.println("cacheProperties -> " + cacheProperties);
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        // 设置key 序列化器
        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        // 设置value 序列化器 JSON格式
        config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));

        // 根据redis有关的所有配置
        CacheProperties.Redis redisProperties = cacheProperties.getRedis();

        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive());
        }

        if (redisProperties.getKeyPrefix() != null) {
            config = config.prefixKeysWith(redisProperties.getKeyPrefix());
        }

        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }

        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }
        // 配置文件中的配置生效
        return config;
    }
}
